package com.bw.controller;

import cn.hutool.core.util.IdUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bw.client.UserClient;
import com.bw.domain.*;
import com.bw.service.ContractInfoService;
import com.bw.service.OrderInfoService;
import com.bw.service.SenderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@Slf4j
public class OrderController {


    @Autowired
    ContractInfoService contractInfoService;


    @Autowired
    UserClient userClient;

    @Autowired
    OrderInfoService orderInfoService;

    @Autowired
    SenderService senderService;


    /**
     * 模拟支付成功，  发送短信
     * @return
     */
    @RequestMapping("/mockOrder")
    public BResult mockOrder() {
        // 给客户发短信  支付成功了
        MyMessage message = MyMessage.builder().type(1).orderNo("428428hgdfgdgedterterer").phone("17611221735").msg("支付成功").build();
        try {
            senderService.sendMsg(message);
        } catch (Exception e) {
            System.out.println("-------mockOrder  发消息失败------");
//            throw new RuntimeException(e);
        }
        return BResult.success("success");

    }

    @RequestMapping("/orderList")
    public BResult orderList() {

        return BResult.success(orderInfoService.list());

    }

    /**
     *  程序都需要手动触发，  VUE  jsp  浏览器   postman  单元测试
     *
     *
     * @param orderId
     * @return
     * @throws AlipayApiException
     */
    @RequestMapping("/toRefund")
    public BResult toRefund(Integer orderId) throws AlipayApiException {

        OrderInfo orderInfo = orderInfoService.getById(orderId);

//获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        String out_trade_no = orderInfo.getOrderNo();
        //支付宝交易号
        String trade_no = orderInfo.getAlipayNo();
        //请二选一设置
        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = orderInfo.getAmount().toString();
        //退款的原因说明
        String refund_reason = "";
        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
        String out_request_no = "";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"trade_no\":\"" + trade_no + "\","
                + "\"refund_amount\":\"" + refund_amount + "\","
                + "\"refund_reason\":\"" + refund_reason + "\","
                + "\"out_request_no\":\"" + out_request_no + "\"}");

        //请求
        AlipayTradeRefundResponse execute = alipayClient.execute(alipayRequest);
        String result = execute.getBody();

        //输出
        //{"alipay_trade_refund_response":{"code":"10000","msg":"Success","buyer_logon_id":"bqp***@sandbox.com","buyer_user_id":"2088722032166476","fund_change":"Y","gmt_refund_pay":"2024-03-28 11:03:29","out_trade_no":"DD1772905732177596416","refund_fee":"166.53","send_back_fee":"0.00","trade_no":"2024032722001466470503500743"},"sign":"JpxH+M0fV2H70eQKePqLW2lXo5D+bTmmAgxtZaSFnXQDpr+hturfqr/UTWksn+7I5jfXT+q66JbvETF+imALi5XC6AQnjlfGoK6m+QKWeKRK5+89ay76WhaDAXlgEnJHA8NEmW5TVjlMOcUisj0+9TL69qxUVvOgQwgmduxvGzo4jKS+/DtQKA5keRA67Xsnw/Ol05vq4KIZiIfOsNoat3+QoMi3oPvF7U9oaN6nYViCIu5cYEJHIdbNBBb1kTDvpLVBcfh8Og+J3GDEU/rREt4J0t0JsPbBQchfJEjGFc0AnB9K3c+3o9oODBg27Y4p6mWYpkYe8j2hpjDdS9xVFA=="}
        System.out.println(result);
        // 退款成功 修改订单状态
        orderInfo.setStatus(2);
        orderInfoService.updateById(orderInfo);
        return BResult.success(result);

    }

    /**
     * 从商品页面去支付  id是商品Id
     * @param request
     * @return
     * @throws AlipayApiException
     */
    @RequestMapping("/toPayByContractId")
    public BResult<String> toPay(Integer contractId, HttpServletRequest request) throws AlipayApiException {
        ContractInfo contractInfo = contractInfoService.getById(contractId);

        BigDecimal price = contractInfo.getPrice();

        //先下单 再支付
        //生成订单号  使用雪花算法 生成 唯一Id
        String orderNo = "DD" + IdUtil.getSnowflakeNextId();
        User user = userClient.selectUserByToken(request.getHeader("token"));
        Integer userId = user.getId();

        OrderInfo orderInfo = OrderInfo.builder().status(0).subject("合同支付").orderNo(orderNo).amount(price).userId(userId).build();

        orderInfoService.save(orderInfo);

//获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderNo;
        //付款金额，必填
        String total_amount = price.toString();
        //订单名称，必填
        String subject = "合同付款";
        //商品描述，可空
        String body = "合同付款";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String html = alipayClient.pageExecute(alipayRequest).getBody();


        return BResult.success(html);
    }

    /**
     * 支付宝 会调用这个方法，  告诉咱们 哪个订单号 支付成功了
     * 接收支付宝 发送过来 支付消息
     */
    @RequestMapping("/callbackAliPay")
    public void callbackAliPay(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {
//获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {
            //商户订单号  自己的订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号  支付宝的订单号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            //     "  update order_info   set alipay_no = #{trade_no}, status = 1  where order_no = #{out_trade_no}  "


            OrderInfo one = orderInfoService.getOne(Wrappers.lambdaQuery(OrderInfo.class).eq(OrderInfo::getOrderNo, out_trade_no));


            Integer userId = one.getUserId();  //   订单上的 用户Id
                // 手机号  邮箱

            orderInfoService.update(Wrappers.lambdaUpdate(OrderInfo.class).set(OrderInfo::getAlipayNo, trade_no).set(OrderInfo::getStatus, 1).eq(OrderInfo::getOrderNo, out_trade_no));



            //支付成功 给客户发短信  支付成功了   生产者 发消息
            MyMessage message = MyMessage.builder().type(1).orderNo(out_trade_no).phone("17611221735").msg("支付成功").build();
            try {
                senderService.sendMsg(message);  // 如果发送异常会执行 三次
            } catch (Exception e) {
                log.error("-------生产者发消息异常---{},,e{}",message,e);  // 如果3次都失败  异常并 打印

            }


            // VUE的列表页
            response.sendRedirect("http://localhost:8080/#/contract");


        } else {
            System.out.println("------验签失败----");
        }
        //——请在这里编写您的程序（以上代码仅作参考）——

    }


}
